import React from 'react';
import { withRouter } from 'react-router';
import { connect } from 'react-redux';
import Dialog from 'rc-dialog';
import Input from '../base/Input.js';
import InputNumber from '../base/InputNumber.js';
import testPackageAction from '../../actions/testPackageAction.js';
import FileUploadTool from '../../utils/FileUploadAPIUtils.js';
import Pregress from '../base/Pregress.js';
import Widget from '../mui/Widget.js';
import HoverMessageOutVersion from '../mui/hoverMessageOutVersion.js';
import HoverMessageProNo from '../mui/hoverMessageProNo.js';
import HoverMessageChannelVer from '../mui/hoverMessageChannelVer.js';
import HoverMessageBulidNo from '../mui/hoverMessageBulidNo.js';
import UploadFileInput from './uploadFileInput.js';
import validate from '../../utils/Validate.js';

const formTestPackage = withRouter(
  React.createClass({
    getInitialState() {
      return {
        uploadFileName:'',
        visible: false,
        reUploadvisible: false,
        uploadVisible: false,
        buttonState: false,
        uploadButton: true,
        projNameError: false,
        channelVerError: false,
        buildNoError: false,
        outVersionError: {},
        formData: {
          name: '',
          low: '',
          high: '',
          proj_name: '',
          channel_ver: '',
          build_no: '',
          finger: '',
          remark: '',
        },
      };
    },
    componentWillMount() {
      this.props.router.setRouteLeaveHook(
        this.props.route,
        this.routerWillLeave
      );
    },
    componentDidMount() {
    // 判断是否传入id(编辑功能)
    // ==================
      if (this.props.params.id) {
        this.props.getOneTestPackage({ id: this.props.params.id });
      }
    },
    componentWillReceiveProps(nextProps) {
      if (!nextProps.saveErrorMsg.name && this.props.params.id) { // 如果保存后台返回错误信息则不更新状态
        this.setState({ buttonState: true });
        const fData = this.state.formData;
        console.log(this.state.formData)
        fData.name = nextProps.oneTestPackage.name;
        // fData.version = nextProps.oneTestPackage.version;
        fData.low = nextProps.oneTestPackage.low;
        fData.high = nextProps.oneTestPackage.high;
        fData.proj_name = nextProps.oneTestPackage.proj_name;
        fData.channel_ver = nextProps.oneTestPackage.channel_ver;
        fData.build_no = nextProps.oneTestPackage.build_no;
        fData.remark = nextProps.oneTestPackage.remark;
        fData.finger = nextProps.oneTestPackage.finger;
        this.setState({
          formData: fData,
        });
      }
    },
    // 离开清理数据
    // ===========
    componentWillUnmount() {
      this.props.restoreTestPackage();
      const { cancelUpload, packageData } = this.props;
      const flog = !(packageData.name); // 是否显示第一个上传按钮
      if (FileUploadTool.abort) {
        FileUploadTool.abort();
        cancelUpload(flog);
      }
    },
    onClick() {
      if ((this.props.prepressData.Pregress > 0 && this.props.prepressData.Pregress !== 100) || this.props.packageData.name) {
        this.setState({ visible: true });
      } else {
        this.leaveFlag = true;
        this.props.router.push('/');
      }
    },
    onClose() {
      this.setState({
        visible: false,
      });
      this.props.cancelUpload();
      this.leaveFlag = true;
      this.props.router.push('/');
    },
    routerWillLeave() {
      const { formData } = this.state;
      if (this.leaveFlag) {
        return true;
      }

      for (const key in formData) {
        if (formData[key] || this.props.packageData.name) {
          return '是否放弃保存当前页面并跳转';
        }
      }
    },
    cancelReturn() {
      this.setState({
        visible: false,
      });
    },
    handleChange(targetData) {
      // 序列化表单
      // ============
      const fData = this.state.formData;
      // if (targetData.name === 'proj_name') {
      //   targetData.value = targetData.value.toLowerCase();
      // }
      fData[targetData.name] = targetData.value;
      this.setState({
        formData: fData,
      });
      // 如果有为空情况，不能点击保存按钮
      // ==============================
      for (const key in fData) {
        if (!fData[key] && key !== 'remark' && key !== 'proj_name') {
          this.setState({ buttonState: false });
          break;
        } else {
          this.setState({ buttonState: true });
        }
      }
    },
    handleBlur(targetData) {
      // 版本格式判断和版本大小比较
      // ======================
      if (!RegExp(validate.version).test(targetData.value)) {
        this.setState({
          outVersionError: {
            error: true,
            message: '格式错误'
          }
        });
        return;
      } else {
        this.setState({
          outVersionError: {
            error: false,
            message: ''
          }
        });
      }
      // 版本补0. 例如： 1.1.2.30  补为01.01.02.30
      // ==========================================
      function transformZero(array) {
        array.forEach((item, index) => {
          if (item.length !== 2) {
            array[index] = `0${item}`;
          }
        });
        return array;
      }
      const { formData } = this.state;
      const low = formData.low.split('.');
      const high = formData.high.split('.');
      const nextLow = transformZero(low).join('.');
      const nextHigh = transformZero(high).join('.');
      if (nextLow >= nextHigh && formData.low && formData.high) {
        this.setState({
          outVersionError: {
            error: true,
            message: '目标版本号必须大于初始版本号'
          }
        });
      }
    },
    handleBlurEn(targetData) {
      if (!targetData.value.length) {
        return;
      }
      if (!RegExp(validate.letter).test(targetData.value)) {
        this.setState({ projNameError: true });
        return;
      } else {
        this.setState({ projNameError: false });
      }
    },
    handleBlurNumVer(targetData) {
      if (targetData.value.length < 3) {
        this.setState({ channelVerError: true });
      } else {
        this.setState({ channelVerError: false });
      }
    },
    handleBlurNumNo(targetData) {
      if (targetData.value.length < 3) {
        this.setState({ buildNoError: true });
      } else {
        this.setState({ buildNoError: false });
      }
    },
    handleCheckSpace(targetData) {
      // 如果有为空情况，不能点击保存按钮
      // ==============================
      const fData = this.state.formData;
      if (targetData.name === 'finger') {
        fData[targetData.name] = targetData.value.trim();
        this.setState({
          formData: fData,
        });
      }
      if (targetData.name === 'remark') {
        fData[targetData.name] = targetData.value.trim();
        this.setState({
          formData: fData,
        });
      }
      for (const key in fData) {
        if (key !== 'size') {
          fData[key] = fData[key].trim();
        }
        if (!fData[key] && key !== 'remark' && key !== 'proj_name') {
          this.setState({ buttonState: false });
          break;
        } else {
          this.setState({ buttonState: true });
        }
      }
    },
    fileChange(e) {
      const { uploadFile, resetUploadErrorMsg } = this.props;
      const data = { filename: 'file', file: e.target.files[0] };
      this.setState({ uploadButton: false });
      resetUploadErrorMsg();
      uploadFile(data);
      // this.setState({uploadFileName: e.target.files[0].name})
    },
    reUploadDialog() {
      if (this.props.packageData.name) {
        this.setState({ reUploadvisible: true });
      } else {
        this.comfirmReUpload();
      }
    },
    cancelReUploadDialog() {
      this.setState({ reUploadvisible: false });
    },
    comfirmReUpload() {
      const { uploadFile, resetUploadErrorMsg, resetUploadData } = this.props;
      resetUploadData();
      this.setState({ reUploadvisible: false });
      const file = document.createElement('input');
      file.type = 'file';
      // file.accept = '.zip';
      file.click();
      file.addEventListener('change', (e) => {
        const data = { filename: 'file', file: e.target.files[0] };
        resetUploadErrorMsg();
        uploadFile(data);
      });
    },
    cancelUploadReturn() {
      this.setState({ uploadVisible: false });
    },
    cancelUploadShowDialog() {
      this.setState({ uploadVisible: true });
    },
    cancelUpload() {
      const { cancelUpload, packageData } = this.props;
      // let data={packageData: {}, uploadPrepress:{}}
      const flog = !(packageData.name); // 是否显示第一个上传按钮
      this.setState({ uploadVisible: false });
      FileUploadTool.abort();
      cancelUpload(flog);
    },
    handleSubmit(event) {
      event.preventDefault();
      // $(this.refs.formbox).find('input,textarea').trigger('focus').trigger('blur');
      if ($('.form-error').length) {
        return;
      }
      const { saveTestPackage, editTestPackage, packageData } = this.props;
      const data = this.state.formData;
      this.leaveFlag = true;
      // 加入附件信息
      // ============
      if (this.props.packageData.name) {
        data.file_name = packageData.name;
        data.size = packageData.size;
        data.md5 = packageData.md5;
        data.bytes = packageData.bytes;
        data.url = packageData.url;
        saveTestPackage(data, this.props.router);
      } else if (this.props.params.id) {
        data.id = this.props.params.id;
        editTestPackage(data, this.props.router);
      }
    },
    render() {
      const button = <button type="submit" className="btn btn-primary" onClick={this.handleSubmit}>保存</button>;
      const disableButton = <button className="btn btn-disable" disabled="disabled">保存</button>;
      const { params, prepressData, saveErrorMsg, packageData, uploadErrorMsg, oneTestPackage } = this.props;
      const { outVersionError, projNameError, channelVerError, buildNoError } = this.state;
      let dialog, reUploadDialog, cancelUploadDialog;
      if (this.state.visible) {
        dialog = (
          <Dialog
            visible={this.state.visible}
            animation="slide-fade"
            maskAnimation="fade"
            // onClose={this.cancelReturn}
            style={{ width: 420 }}
            // title={<div>第二个弹框</div>}
            footer={
            [
              <button type="button" className="btn btn-cancel w120 mr60" key="close" onClick={this.onClose} >
                确定
              </button>,
              <button type="button" className="btn btn-primary w120" key="save" onClick={this.cancelReturn} >
                取消
              </button>,
            ]
            }
          >
            <div className="confirm-dialog-body">
              <p className="dialog-message">是否确定舍弃</p>
              <p className="fixed-width-text package-name">{packageData.name}</p>
            </div>
          </Dialog>
        );
      }
      if (this.state.reUploadvisible) {
        reUploadDialog = (
          <Dialog
            visible={this.state.reUploadvisible}
            animation="slide-fade"
            maskAnimation="fade"
            // onClose={this.cancelReturn}
            style={{ width: 420 }}
            // title={<div>第二个弹框</div>}
            footer={
            [
              <button type="button" className="btn btn-cancel w120 mr60" key="close" onClick={this.comfirmReUpload} >
                确定
              </button>,
              <button type="button" className="btn btn-primary w120" key="save" onClick={this.cancelReUploadDialog} >
                取消
              </button>,
            ]
            }
          >
            <div className="confirm-dialog-body">
              <p className="dialog-message">是否确定舍弃</p>
              <p className="fixed-width-text package-name">{packageData.name}</p>
            </div>
          </Dialog>
        );
      }
      if (this.state.uploadVisible) {
        cancelUploadDialog = (
          <Dialog
            visible={this.state.uploadVisible}
            animation="slide-fade"
            maskAnimation="fade"
            // onClose={this.cancelReturn}
            style={{ width: 420 }}
            // title={<div>第二个弹框</div>}
            footer={
            [
              <button type="button" className="btn btn-cancel w120 mr60" key="close" onClick={this.cancelUpload} >
                确定
              </button>,
              <button type="button" className="btn btn-primary w120" key="save" onClick={this.cancelUploadReturn} >
                取消
              </button>,
            ]
            }
          >
            <div className="confirm-dialog-body">
              <p className="dialog-message">是否确定舍弃</p>
              <p className="fixed-width-text package-name">{packageData.name}</p>
            </div>
          </Dialog>
        );
      }

      const packageName = <span className="fixed-width-text mw350">{packageData.name}</span>;
      const uploadInput = <UploadFileInput  onChange={this.fileChange} className={"btn btn-primary w160 relative mr15"} id={'upload_file'} />;
      let uploadRender;
      // 判断显示上传按钮否
      // ==================
      if (this.state.uploadButton) {
        uploadRender = uploadInput;
      } else if (packageData.name && !prepressData.Pregress && uploadErrorMsg.code !== 90002 && uploadErrorMsg.code !== 406) {
        uploadRender = packageName;
      }
      // 判断显示错误信息
      // =================
      let showUploadErrorMsg;
      let showRepeatUpload;
      let showPackageSize;
      let showPackageMd5;
      if (uploadErrorMsg.code === 90002) {
        showUploadErrorMsg = <span className="text-danger mr160">该包已经上传，请重新上传。</span>;
        showRepeatUpload = true;
      } else if (uploadErrorMsg.code === 406) {
        showUploadErrorMsg = <span className="text-danger mr160">文件包信息错误。</span>;
        showRepeatUpload = true;
      }
      // 判断显示重新上传按钮
      // ====================
      if ((packageData.name && !prepressData.Pregress) || (!packageData.name && !this.state.uploadButton)) {
        showRepeatUpload = true;
      }
      // 判断显示包大小,MD5码
      // ====================
      if (this.props.params.id) {
        showPackageSize = <p>{oneTestPackage.size} M</p>;
        showPackageMd5 = <p>{oneTestPackage.md5}</p>;
      } else if (packageData.md5) {
        showPackageSize = <p>{packageData.size} {packageData.size ? 'M' : ''}</p>;
        showPackageMd5 = <p>{packageData.md5}</p>;
      } else {
        showPackageSize = <p className="init-message">测试包上传后自动获取</p>;
        showPackageMd5 = <p className="init-message">上传时自动生成</p>;
      }
      // const v1 = { data: {} };
      // const v2 = {};
      // v1.data[validate.letter] = '格式错误，请填写0-2位字母';
      // v1.minLengthChar = { min:0, message: '' };
      // v2.minLengthChar = { min:3, message:'格式错误，请填写3位数字' };
      // v2.maxLengthChar = { max:3, message:'格式错误，请填写3位数字' };
      return (
        <div className="mw600">
          {
            params.id ?
              <Widget widgetHeader={'测试包侯选池'} widgetHeaderTwo={'编辑测试包'} />
            :
              <Widget widgetHeader={'上传测试包'} />
          }
          <div className="form-group">
            <label className="control-label w120" htmlFor="upload_file">上传</label>
            {params.id ?
              <span>{oneTestPackage.filename}</span>
              :
              <div className="input-group">
                {uploadRender}
                {prepressData.Pregress > 0 && uploadErrorMsg.code !== 90002 ? <Pregress Pregress={prepressData.Pregress} /> : ''}
                {prepressData.Pregress > 0 && prepressData.Pregress < 100 ? <a onClick={this.cancelUploadShowDialog}>取消上传</a> : ''}
                {showUploadErrorMsg}
                {showRepeatUpload && !prepressData.Pregress ? <a onClick={this.reUploadDialog}>重新上传</a> : ''}
                {
                  // <UploadFileInput accept={".zip"} onChange={this.fileChange} buttonMsg={'重新上传'} /> : ''
                }
              </div>
            }
          </div>
          <form className="f-group-480">
            <div className="form-group">
              <label className="control-label w120" htmlFor="name">包命名</label>
              <div className="input-group">
                <Input
                  data-target="name"
                  type="text"
                  value={this.state.formData.name}
                  onChange={this.handleChange}
                  placeholder="(必填, 唯一标识, 不可重复。)"
                  maxLength={128}
                />
              </div>
              {saveErrorMsg.name === 'name' ? <span className="form-out-error text-danger" >包命名重复，请重新输入</span> : ''}
            </div>
            <div className="form-group">
              <label className="control-label w120" htmlFor="size">包大小</label>
              <div className="input-group">
              {showPackageSize}
              </div>
            </div>
            <div className="form-group f-group-160">
              <label className="control-label w120" htmlFor="version">外部版本号区间</label>
              <span>从</span>
              <div className="input-group">
                <Input
                  data-target="low"
                  type="text"
                  onChange={this.handleChange}
                  value={this.state.formData.low}
                  placeholder="(必填,示列: 1.0.2.5)"
                  onBlur={this.handleBlur}
                  // disabled={params.id}
                />
              </div>
              <span>到</span>
              <div className="input-group">
                <Input
                  data-target="high"
                  type="text"
                  onChange={this.handleChange}
                  value={this.state.formData.high}
                  placeholder="(必填,示列: 1.0.2.6)"
                  onBlur={this.handleBlur}
                  // disabled={params.id}
                />
              </div>
              <HoverMessageOutVersion />
              {outVersionError.error ? <span className="form-error text-danger">{outVersionError.message}</span> : ''}
            </div>
            <div className="form-group">
              <label className="control-label w120">项目识别码</label>
              <div className="input-group placeholder-normal">
                <Input
                  data-target="proj_name"
                  type="text"
                  onChange={this.handleChange}
                  value={this.state.formData.proj_name}
                  placeholder="(0-2位字母)"
                  onBlur={this.handleBlurEn}
                  maxLength={2}
                />
                <HoverMessageProNo />
                {projNameError ? <span className="form-error text-danger">格式错误，请填写0-2位字母</span> : ''}
              </div>
            </div>
            <div className="form-group">
              <label className="control-label w120" htmlFor="version">渠道识别码</label>
              <div className="input-group">
                <InputNumber
                  data-target="channel_ver"
                  type="text"
                  onChange={this.handleChange}
                  value={this.state.formData.channel_ver}
                  placeholder="(必填, 3位数字)"
                  onBlur={this.handleBlurNumVer}
                  maxLength={3}
                />
                <HoverMessageChannelVer />
                {channelVerError ? <span className="form-error text-danger">格式错误，请填写3位数字</span> : ''}
              </div>
            </div>
            <div className="form-group">
              <label className="control-label w120" htmlFor="version">Build号</label>
              <div className="input-group">
                <InputNumber
                  data-target="build_no"
                  type="text"
                  onChange={this.handleChange}
                  value={this.state.formData.build_no}
                  placeholder="(必填, 3位数字)"
                  onBlur={this.handleBlurNumNo}
                  maxLength={3}
                />
                <HoverMessageBulidNo />
                {buildNoError ? <span className="form-error text-danger">格式错误，请填写3位数字</span> : ''}
              </div>
            </div>
            <div className="form-group">
              <label className="control-label w120" htmlFor="md5">MD5码</label>
              <div className="input-group">
              {showPackageMd5}
              </div>
            </div>
            <div className="form-group">
              <label className="control-label w120" htmlFor="finger">指纹</label>
              <div className="input-group">
                <Input
                  data-target="finger"
                  type="text"
                  onChange={this.handleChange}
                  value={this.state.formData.finger}
                  placeholder="(必填)"
                  onBlur={this.handleCheckSpace}
                />
              </div>
            </div>
            <div className="form-group">
              <label className="control-label w120" htmlFor="remark">备注</label>
              <div className="input-group placeholder-normal">
                <Input
                  data-target="remark"
                  type="textarea"
                  onChange={this.handleChange}
                  value={this.state.formData.remark}
                  onBlur={this.handleCheckSpace}
                  rows={'4'}
                  placeholder="(选填)"
                />
              </div>
            </div>
            <div className="ml108">
              {this.state.buttonState && (packageData.md5 || oneTestPackage.md5) ? button : disableButton}
              <a onClick={this.onClick} className="btn btn-cancel ml48">取消</a>
            </div>
          </form>
          {dialog}
          {reUploadDialog}
          {cancelUploadDialog}
        </div>
      );
    },
  })
);

const mapStateToProps = function (state) {
  return {
    packageData: state.testPackage.uploadData,
    prepressData: state.testPackage.uploadPrepress,
    saveErrorMsg: state.testPackage.testPackageMsg,
    uploadErrorMsg: state.testPackage.uploadMsg,
    oneTestPackage: state.testPackage.oneTestPackage,
    uploadButton: state.testPackage.uploadButton
  };
};

module.exports = connect(mapStateToProps, testPackageAction)(formTestPackage);
